package com.thunder.soft.ui.activity;

import android.content.Intent;
import android.widget.Toast;

import androidx.lifecycle.Observer;

import com.thunder.soft.R;
import com.thunder.soft.bean.UserBean;
import com.thunder.soft.common.base.BaseActivity;
import com.thunder.soft.common.util.SharedPreferenceUtils;
import com.thunder.soft.common.util.ViewModelProviderHelper;
import com.thunder.soft.databinding.ActivityLoginBinding;
import com.thunder.soft.vm.LoginViewModel;

import java.util.Map;

public class LoginActivity extends BaseActivity<ActivityLoginBinding> {
    private LoginViewModel loginViewModel;
    private static String TAG = LoginActivity.class.getName();

    @Override
    protected void initData() {
        loginViewModel = ViewModelProviderHelper.buildViewModel(this, LoginViewModel.class);
        getLifecycle().addObserver(loginViewModel);
        binding.setLoginViewModel(loginViewModel);

        loginViewModel.getErrorMsg().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                Toast.makeText(LoginActivity.this, s, Toast.LENGTH_SHORT).show();
            }
        });

        loginViewModel.getLiveData().observe(this, new Observer<UserBean>() {
            @Override
            public void onChanged(UserBean userBeans) {
                SharedPreferenceUtils.getInstance().put(LoginActivity.this,"username",userBeans.getUsername());
                SharedPreferenceUtils.getInstance().put(LoginActivity.this,"id",String.valueOf(userBeans.getId()));
                startActivity(new Intent(LoginActivity.this,MainActivity.class));
            }
        });

        loginViewModel.getFinishActivity().observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                finish();
            }
        });

        loginViewModel.getActivityLiveData().observe(this, new Observer<Map<String, Object>>() {
            @Override
            public void onChanged(Map<String, Object> value) {
                Class<RegisterActivity> activity = (Class<RegisterActivity>) value.get("activity");
                if(activity != null){
                    startActivity(activity);
                }
            }
        });
    }

    @Override
    protected int layoutId() {
        return R.layout.activity_login;
    }
}